package com.atguigu.autoconfig;

import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;

@SpringBootConfiguration
@EnableConfigurationProperties(DataSourceProperties.class)
public class DataSourceAutoConfiguration {
    @Autowired
    DataSourceProperties dataSourceProperties ;

    @Bean
    @ConditionalOnProperty(value = "spring.jdbc.datasource.type" ,havingValue = "druid")
    public DataSource createDataSource() {
        DruidDataSource dataSource = new DruidDataSource() ;
        dataSource.setDriverClassName(dataSourceProperties.getDriver());
        dataSource.setUrl(dataSourceProperties.getUrl());
        dataSource.setUsername(dataSourceProperties.getUserName());
        dataSource.setPassword(dataSourceProperties.getPassword());
        return dataSource ;
    }

    @Bean
    @ConditionalOnProperty(value = "spring.jdbc.datasource.type",havingValue = "c3p0")
    public DataSource createC3P0DataSource() throws Exception {
        ComboPooledDataSource c3p0 = new ComboPooledDataSource();
        c3p0.setDriverClass(dataSourceProperties.getDriver());
        c3p0.setJdbcUrl(dataSourceProperties.getUrl());
        c3p0.setUser(dataSourceProperties.getUserName());
        c3p0.setPassword(dataSourceProperties.getPassword());
        return c3p0 ;
    }
}
